import { useState, useEffect, useRef } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { 
  Upload, 
  Download, 
  Search, 
  Filter,
  FileSpreadsheet,
  Database,
  Globe,
  CheckCircle,
  AlertCircle,
  Clock
} from 'lucide-react'
import { toast } from 'sonner'
import apiService from '../services/api'

export default function DataManagement() {
  const [uploadProgress, setUploadProgress] = useState(0)
  const [isUploading, setIsUploading] = useState(false)
  const [searchTerm, setSearchTerm] = useState('')
  const [historicalData, setHistoricalData] = useState([])
  const [industryData, setIndustryData] = useState([])
  const [companies, setCompanies] = useState([])
  const [loading, setLoading] = useState(false)
  const [filters, setFilters] = useState({
    company_id: '',
    product_id: '',
    year: ''
  })
  const fileInputRef = useRef(null)

  useEffect(() => {
    loadData()
    loadCompanies()
    loadIndustryData()
  }, [])

  const loadData = async () => {
    try {
      setLoading(true)
      const params = { ...filters, page: 1, page_size: 50 }
      Object.keys(params).forEach(key => {
        if (!params[key]) delete params[key]
      })

      const response = await apiService.getHistoricalData(params)
      const items = response.data?.items || []
      
      setHistoricalData(items.map(item => ({
        id: item.id,
        product: item.product_name,
        year: item.year,
        sales: item.sales_amount,
        growth: item.yoy_growth_rate,
        status: 'verified'
      })))
    } catch (error) {
      console.error('加载历史数据失败:', error)
      // 使用模拟数据作为后备
      setHistoricalData([
        { id: 1, product: '阿司匹林', year: 2023, sales: 850, growth: 8.5, status: 'verified' },
        { id: 2, product: '布洛芬', year: 2023, sales: 720, growth: 12.3, status: 'verified' },
        { id: 3, product: '对乙酰氨基酚', year: 2023, sales: 650, growth: -2.1, status: 'pending' },
        { id: 4, product: '维生素C', year: 2023, sales: 580, growth: 15.7, status: 'verified' }
      ])
    } finally {
      setLoading(false)
    }
  }

  const loadCompanies = async () => {
    try {
      const response = await apiService.getCompanies()
      setCompanies(response.data || [])
    } catch (error) {
      console.error('加载公司列表失败:', error)
    }
  }

  const loadIndustryData = async () => {
    try {
      const response = await apiService.getIndustryData({ page: 1, page_size: 10 })
      const items = response.data?.items || []
      
      setIndustryData(items.map(item => ({
        id: item.id,
        source: item.source,
        title: item.title,
        date: item.publish_date || item.created_at,
        status: 'updated'
      })))
    } catch (error) {
      console.error('加载行业数据失败:', error)
      // 使用模拟数据作为后备
      setIndustryData([
        { id: 1, source: '国家统计局', title: '2024年医药制造业统计数据', date: '2024-01-15', status: 'updated' },
        { id: 2, source: '中国医药工业信息中心', title: '医药行业发展报告', date: '2024-01-10', status: 'crawling' },
        { id: 3, source: '证券研究报告', title: '医药板块投资分析', date: '2024-01-08', status: 'failed' }
      ])
    }
  }

  const handleFileUpload = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    setIsUploading(true)
    setUploadProgress(0)

    try {
      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval)
            return 90
          }
          return prev + 10
        })
      }, 200)

      await apiService.importData(file)
      
      clearInterval(progressInterval)
      setUploadProgress(100)
      
      toast.success('数据导入成功')
      loadData() // 重新加载数据
    } catch (error) {
      console.error('文件上传失败:', error)
      toast.error(error.message || '文件上传失败')
    } finally {
      setIsUploading(false)
      setUploadProgress(0)
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  const handleStartCrawl = async () => {
    try {
      await apiService.startCrawlTask({
        sources: ['stats.gov.cn', 'pharmnet.com.cn'],
        keywords: ['医药', '制药', '药品']
      })
      toast.success('爬取任务已启动')
      loadIndustryData() // 重新加载数据
    } catch (error) {
      console.error('启动爬取任务失败:', error)
      toast.error('启动爬取任务失败')
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'verified':
      case 'updated':
        return <CheckCircle className="h-4 w-4 text-green-500" />
      case 'pending':
      case 'crawling':
        return <Clock className="h-4 w-4 text-yellow-500" />
      case 'failed':
        return <AlertCircle className="h-4 w-4 text-red-500" />
      default:
        return <Clock className="h-4 w-4 text-gray-500" />
    }
  }

  const getStatusBadge = (status) => {
    const variants = {
      verified: 'default',
      updated: 'default',
      pending: 'secondary',
      crawling: 'secondary',
      failed: 'destructive'
    }
    const labels = {
      verified: '已验证',
      updated: '已更新',
      pending: '待处理',
      crawling: '爬取中',
      failed: '失败'
    }
    return <Badge variant={variants[status]}>{labels[status]}</Badge>
  }

  const filteredHistoricalData = historicalData.filter(item =>
    item.product.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const filteredIndustryData = industryData.filter(item =>
    item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.source.toLowerCase().includes(searchTerm.toLowerCase())
  )

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">数据管理</h1>
          <p className="text-gray-600 mt-1">管理历史经营数据和行业数据</p>
        </div>
        <div className="flex space-x-3">
          <Button variant="outline" onClick={() => fileInputRef.current?.click()}>
            <Upload className="h-4 w-4 mr-2" />
            导入数据
          </Button>
          <Button onClick={handleStartCrawl}>
            <Globe className="h-4 w-4 mr-2" />
            爬取行业数据
          </Button>
        </div>
      </div>

      {/* File Upload */}
      <input
        ref={fileInputRef}
        type="file"
        accept=".xlsx,.xls,.csv"
        onChange={handleFileUpload}
        className="hidden"
      />

      {/* Upload Progress */}
      {isUploading && (
        <Card>
          <CardContent className="pt-6">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">上传进度</span>
                <span className="text-sm text-gray-500">{uploadProgress}%</span>
              </div>
              <Progress value={uploadProgress} className="w-full" />
            </div>
          </CardContent>
        </Card>
      )}

      {/* Search */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center space-x-4">
            <div className="flex-1">
              <Label htmlFor="search">搜索</Label>
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  id="search"
                  placeholder="搜索产品名称、公司或数据源..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Button variant="outline">
              <Filter className="h-4 w-4 mr-2" />
              筛选
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Data Tabs */}
      <Tabs defaultValue="historical" className="space-y-4">
        <TabsList>
          <TabsTrigger value="historical">
            <Database className="h-4 w-4 mr-2" />
            历史经营数据
          </TabsTrigger>
          <TabsTrigger value="industry">
            <Globe className="h-4 w-4 mr-2" />
            行业数据
          </TabsTrigger>
        </TabsList>

        {/* Historical Data Tab */}
        <TabsContent value="historical">
          <Card>
            <CardHeader>
              <CardTitle>历史经营数据</CardTitle>
              <CardDescription>
                管理和查看历史销售数据，支持Excel/CSV格式导入
              </CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="text-center py-8 text-gray-500">
                  加载中...
                </div>
              ) : (
                <div className="space-y-4">
                  {filteredHistoricalData.map((item) => (
                    <div key={item.id} className="flex items-center justify-between p-4 border rounded-lg">
                      <div className="flex items-center space-x-4">
                        <FileSpreadsheet className="h-8 w-8 text-blue-500" />
                        <div>
                          <p className="font-medium text-gray-900">{item.product}</p>
                          <p className="text-sm text-gray-500">
                            {item.year}年 • 销售额: {item.sales}万元 • 增长率: {item.growth}%
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center space-x-3">
                        {getStatusIcon(item.status)}
                        {getStatusBadge(item.status)}
                        <Button variant="ghost" size="sm">
                          查看详情
                        </Button>
                      </div>
                    </div>
                  ))}
                  {filteredHistoricalData.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      暂无数据
                    </div>
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Industry Data Tab */}
        <TabsContent value="industry">
          <Card>
            <CardHeader>
              <CardTitle>行业数据</CardTitle>
              <CardDescription>
                自动爬取的行业数据和市场信息
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {filteredIndustryData.map((item) => (
                  <div key={item.id} className="flex items-center justify-between p-4 border rounded-lg">
                    <div className="flex items-center space-x-4">
                      <Globe className="h-8 w-8 text-green-500" />
                      <div>
                        <p className="font-medium text-gray-900">{item.title}</p>
                        <p className="text-sm text-gray-500">
                          {item.source} • {item.date}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      {getStatusIcon(item.status)}
                      {getStatusBadge(item.status)}
                      <Button variant="ghost" size="sm">
                        查看详情
                      </Button>
                    </div>
                  </div>
                ))}
                {filteredIndustryData.length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    暂无数据
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}

